<template>
  <div class="dashboard-page">
    <div class="page-header">
      <h1 class="page-title">📊 监控面板</h1>
      <p class="page-description">实时监控API路由器的运行状态和性能指标</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card requests">
        <div class="stat-icon">🚀</div>
        <div class="stat-content">
          <h3>总请求数</h3>
          <p class="stat-number">{{ formatNumber(stats.totalRequests) }}</p>
          <span class="stat-change positive">+{{ stats.requestsToday }} 今日</span>
        </div>
      </div>
      
      <div class="stat-card success">
        <div class="stat-icon">✅</div>
        <div class="stat-content">
          <h3>成功请求</h3>
          <p class="stat-number">{{ formatNumber(stats.successfulRequests) }}</p>
          <span class="stat-change positive">{{ successRate }}% 成功率</span>
        </div>
      </div>
      
      <div class="stat-card errors">
        <div class="stat-icon">❌</div>
        <div class="stat-content">
          <h3>失败请求</h3>
          <p class="stat-number">{{ formatNumber(stats.failedRequests) }}</p>
          <span class="stat-change negative">{{ errorRate }}% 错误率</span>
        </div>
      </div>
      
      <div class="stat-card latency">
        <div class="stat-icon">⚡</div>
        <div class="stat-content">
          <h3>平均延迟</h3>
          <p class="stat-number">{{ stats.avgLatency }}ms</p>
          <span class="stat-change" :class="latencyTrend">{{ latencyChange }}ms vs 昨日</span>
        </div>
      </div>
    </div>

    <!-- 活跃模型和实时状态 -->
    <div class="dashboard-grid">
      <!-- 活跃模型 -->
      <div class="dashboard-card">
        <div class="card-header">
          <h2>🤖 活跃模型</h2>
          <button @click="refreshModels" class="refresh-btn" :disabled="isRefreshing">
            {{ isRefreshing ? '刷新中...' : '刷新' }}
          </button>
        </div>
        <div class="card-content">
          <div v-if="models.length === 0" class="empty-state">
            <p>暂无活跃模型</p>
          </div>
          <div v-else class="model-list">
            <div v-for="model in models" :key="model.id" class="model-item">
              <div class="model-info">
                <span class="model-name">{{ model.name }}</span>
                <span class="model-type" :class="model.type">{{ model.type.toUpperCase() }}</span>
              </div>
              <div class="model-stats">
                <span class="requests-count">{{ model.requestCount || 0 }} 请求</span>
                <span class="status-indicator" :class="getModelStatus(model)"></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时日志 -->
      <div class="dashboard-card">
        <div class="card-header">
          <h2>📝 实时日志</h2>
          <button @click="clearLogs" class="clear-btn">清空</button>
        </div>
        <div class="card-content">
          <div class="logs-container">
            <div v-if="logs.length === 0" class="empty-state">
              <p>暂无日志记录</p>
            </div>
            <div v-else class="log-list">
              <div v-for="log in logs.slice(-10)" :key="log.id" class="log-item" :class="log.level">
                <span class="log-time">{{ formatTime(log.timestamp) }}</span>
                <span class="log-level">{{ log.level.toUpperCase() }}</span>
                <span class="log-message">{{ log.message }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能图表区域 -->
    <div class="chart-section">
      <div class="dashboard-card full-width">
        <div class="card-header">
          <h2>📈 请求趋势</h2>
          <div class="time-filter">
            <button 
              v-for="period in timePeriods" 
              :key="period.value"
              @click="selectedPeriod = period.value"
              :class="{ active: selectedPeriod === period.value }"
              class="period-btn"
            >
              {{ period.label }}
            </button>
          </div>
        </div>
        <div class="card-content">
          <div class="chart-placeholder">
            <div class="chart-mock">
              <div class="chart-bars">
                <div v-for="i in 12" :key="i" class="chart-bar" :style="{ height: Math.random() * 100 + '%' }"></div>
              </div>
              <p class="chart-label">请求量趋势图 (模拟数据)</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stats: {
        totalRequests: 0,
        successfulRequests: 0,
        failedRequests: 0,
        avgLatency: 0,
        requestsToday: 0
      },
      models: [],
      logs: [],
      isRefreshing: false,
      selectedPeriod: '24h',
      timePeriods: [
        { label: '1小时', value: '1h' },
        { label: '24小时', value: '24h' },
        { label: '7天', value: '7d' },
        { label: '30天', value: '30d' }
      ],
      refreshInterval: null
    };
  },
  computed: {
    successRate() {
      if (this.stats.totalRequests === 0) return 0;
      return Math.round((this.stats.successfulRequests / this.stats.totalRequests) * 100);
    },
    errorRate() {
      if (this.stats.totalRequests === 0) return 0;
      return Math.round((this.stats.failedRequests / this.stats.totalRequests) * 100);
    },
    latencyChange() {
      // 模拟延迟变化
      return Math.floor(Math.random() * 20) - 10;
    },
    latencyTrend() {
      return this.latencyChange >= 0 ? 'negative' : 'positive';
    }
  },
  async mounted() {
    await this.fetchStats();
    await this.fetchModels();
    this.generateMockLogs();
    
    // 设置定时刷新
    this.refreshInterval = setInterval(() => {
      this.fetchStats();
      this.addRandomLog();
    }, 5000);
  },
  beforeDestroy() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  },
  methods: {
    async fetchStats() {
      try {
        // 在实际应用中，这里应该从后端API获取真实数据
        // 现在使用模拟数据
        this.stats = {
          totalRequests: Math.floor(Math.random() * 5000) + 1000,
          successfulRequests: Math.floor(Math.random() * 4500) + 900,
          failedRequests: Math.floor(Math.random() * 200) + 10,
          avgLatency: Math.floor(Math.random() * 300) + 50,
          requestsToday: Math.floor(Math.random() * 500) + 50
        };
      } catch (error) {
        console.error('Error fetching stats:', error);
      }
    },
    async fetchModels() {
      try {
        const response = await fetch('/api/models');
        this.models = await response.json();
        
        // 为每个模型添加模拟的请求计数
        this.models = this.models.map(model => ({
          ...model,
          requestCount: Math.floor(Math.random() * 100),
          status: Math.random() > 0.2 ? 'online' : 'offline'
        }));
      } catch (error) {
        console.error('Error fetching models:', error);
      }
    },
    async refreshModels() {
      this.isRefreshing = true;
      try {
        await this.fetchModels();
        this.$message?.success('模型列表已刷新');
      } catch (error) {
        this.$message?.error('刷新失败');
      } finally {
        this.isRefreshing = false;
      }
    },
    generateMockLogs() {
      const logLevels = ['info', 'warning', 'error', 'success'];
      const messages = [
        '模型请求处理完成',
        '新的API连接建立',
        '模型响应超时',
        '用户认证成功',
        '数据库连接异常',
        '缓存更新完成',
        '负载均衡调整',
        '系统性能监控'
      ];
      
      for (let i = 0; i < 5; i++) {
        this.logs.push({
          id: Date.now() + i,
          level: logLevels[Math.floor(Math.random() * logLevels.length)],
          message: messages[Math.floor(Math.random() * messages.length)],
          timestamp: new Date(Date.now() - Math.random() * 3600000)
        });
      }
    },
    addRandomLog() {
      const logLevels = ['info', 'warning', 'error', 'success'];
      const messages = [
        '新的API请求处理',
        '模型切换完成',
        '连接池状态更新',
        '请求队列处理',
        '性能指标更新'
      ];
      
      this.logs.push({
        id: Date.now(),
        level: logLevels[Math.floor(Math.random() * logLevels.length)],
        message: messages[Math.floor(Math.random() * messages.length)],
        timestamp: new Date()
      });
      
      // 保持日志数量在合理范围内
      if (this.logs.length > 50) {
        this.logs = this.logs.slice(-30);
      }
    },
    clearLogs() {
      this.logs = [];
      this.$message?.success('日志已清空');
    },
    formatNumber(num) {
      if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
      }
      return num.toString();
    },
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    getModelStatus(model) {
      return model.status || 'unknown';
    }
  }
};
</script>

<style scoped>
.dashboard-page {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
  color: white;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.page-description {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.stat-icon {
  font-size: 2.5rem;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.stat-content h3 {
  margin: 0 0 8px 0;
  color: #6b7280;
  font-size: 0.9rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-number {
  margin: 0 0 4px 0;
  font-size: 2rem;
  font-weight: 700;
  color: #1f2937;
}

.stat-change {
  font-size: 0.875rem;
  font-weight: 500;
}

.stat-change.positive {
  color: #10b981;
}

.stat-change.negative {
  color: #ef4444;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

.dashboard-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  overflow: hidden;
}

.card-header {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}

.refresh-btn, .clear-btn {
  background: rgba(255,255,255,0.2);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.refresh-btn:hover:not(:disabled), .clear-btn:hover {
  background: rgba(255,255,255,0.3);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.card-content {
  padding: 24px;
}

.empty-state {
  text-align: center;
  color: #6b7280;
  padding: 32px 16px;
}

.model-list {
  space-y: 12px;
}

.model-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8fafc;
  border-radius: 8px;
  margin-bottom: 8px;
}

.model-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.model-name {
  font-weight: 500;
  color: #1f2937;
}

.model-type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
}

.model-type.ollama {
  background: #dbeafe;
  color: #1e40af;
}

.model-type.openai {
  background: #dcfce7;
  color: #166534;
}

.model-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.requests-count {
  font-size: 0.875rem;
  color: #6b7280;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-indicator.online {
  background: #10b981;
}

.status-indicator.offline {
  background: #ef4444;
}

.status-indicator.unknown {
  background: #6b7280;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
}

.log-list {
  space-y: 8px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 0.875rem;
  margin-bottom: 4px;
}

.log-item.info {
  background: #eff6ff;
  border-left: 3px solid #3b82f6;
}

.log-item.success {
  background: #f0fdf4;
  border-left: 3px solid #10b981;
}

.log-item.warning {
  background: #fffbeb;
  border-left: 3px solid #f59e0b;
}

.log-item.error {
  background: #fef2f2;
  border-left: 3px solid #ef4444;
}

.log-time {
  color: #6b7280;
  font-family: monospace;
  min-width: 80px;
}

.log-level {
  font-weight: 600;
  min-width: 60px;
}

.log-level.INFO {
  color: #3b82f6;
}

.log-level.SUCCESS {
  color: #10b981;
}

.log-level.WARNING {
  color: #f59e0b;
}

.log-level.ERROR {
  color: #ef4444;
}

.log-message {
  flex: 1;
  color: #374151;
}

.chart-section {
  margin-bottom: 32px;
}

.full-width {
  grid-column: 1 / -1;
}

.time-filter {
  display: flex;
  gap: 8px;
}

.period-btn {
  padding: 6px 12px;
  background: rgba(255,255,255,0.2);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.period-btn:hover {
  background: rgba(255,255,255,0.3);
}

.period-btn.active {
  background: rgba(255,255,255,0.4);
  font-weight: 600;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-mock {
  text-align: center;
  width: 100%;
}

.chart-bars {
  display: flex;
  align-items: end;
  justify-content: center;
  gap: 8px;
  height: 200px;
  margin-bottom: 16px;
}

.chart-bar {
  width: 24px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  border-radius: 4px 4px 0 0;
  min-height: 20px;
  animation: chartGrow 1s ease-out;
}

@keyframes chartGrow {
  from {
    height: 0;
  }
  to {
    height: var(--final-height);
  }
}

.chart-label {
  color: #6b7280;
  font-size: 0.875rem;
  margin: 0;
}

@media (max-width: 1024px) {
  .dashboard-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .dashboard-page {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .card-header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .time-filter {
    flex-wrap: wrap;
  }
}
</style>